package com.uzai.console.service.fd.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.fd.fddeviceplan.FdDevicePlanIdDto;
import com.uzai.console.dto.fd.fdfollowconfig.FdFollowConfigDto;
import com.uzai.console.dto.fd.fdfollowconfig.FdFollowConfigIdDto;
import com.uzai.console.dto.fd.fdfollowconfig.FdFollowConfigQuery;
import com.uzai.console.dto.fd.fdfollowconfig.FdFollowConfigStatusDto;
import com.uzai.console.dto.remoteapi.RefreshDownloadImgGroupWxidListDto;
import com.uzai.console.entity.Device;
import com.uzai.console.entity.FdDevicePlan;
import com.uzai.console.entity.FdFollowConfig;
import com.uzai.console.entity.es.EsWorkWxGroupInfo;
import com.uzai.console.entity.es.EsWorkWxGroupMember;
import com.uzai.console.entity.es.EsWxContacts;
import com.uzai.console.entity.es.EsWxGroupMember;
import com.uzai.console.mapper.FdDevicePlanMapper;
import com.uzai.console.mapper.FdFollowConfigMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.fd.FdDevicePlanService;
import com.uzai.console.service.fd.FdFollowConfigService;
import com.uzai.console.service.feign.UzaiImClientFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.vo.fd.fddeviceplan.FdDevicePlanVo;
import com.uzai.console.vo.fd.fdfollowconfig.FdFollowConfigVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 发单跟发配置
 *
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class FdFollowConfigServiceImpl implements FdFollowConfigService {

    Logger logger = LoggerFactory.getLogger(FdFollowConfigServiceImpl.class);

    @Autowired
    private FdFollowConfigMapper fdFollowConfigMapper;
    @Autowired
    private UzaiImClientFeignService uzaiImClientFeignService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private FdDevicePlanMapper fdDevicePlanMapper;
    @Autowired
    private FdDevicePlanService fdDevicePlanService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;


    /**
     * 查询发单跟发配置列表
     *
     * @param fdFollowConfigQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Page<FdFollowConfigVo> findFdFollowConfigList(FdFollowConfigQuery fdFollowConfigQuery) {
        //新建返回到页面的LIST对象
        List<FdFollowConfigVo> fdFollowConfigPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<FdFollowConfig> page = new Page<>();
        fdFollowConfigQuery.convert(page);
        ArrayList<FdFollowConfig> fdFollowConfigList = fdFollowConfigMapper.findByList(page, fdFollowConfigQuery);
        if (fdFollowConfigList != null && fdFollowConfigList.size() > 0) {
            for (FdFollowConfig fdFollowConfig : fdFollowConfigList) {
                FdFollowConfigVo fdFollowConfigPageVo = new FdFollowConfigVo();
                BeanUtils.copyProperties(fdFollowConfig, fdFollowConfigPageVo);

                //设备方案名称
                if (fdFollowConfig.getFdDevicePlanId() != null) {
                    FdDevicePlan fdDevicePlan = fdDevicePlanMapper.selectById(fdFollowConfig.getFdDevicePlanId(), fdFollowConfig.getMerId());
                    if (fdDevicePlan != null) {
                        fdFollowConfigPageVo.setFdDevicePlanName(fdDevicePlan.getName());
                    }
                }

                //封装关键词过滤
                if (StringUtils.isNotBlank(fdFollowConfig.getIgnore())) {
                    List<String> ignoreList = JSONObject.parseArray(fdFollowConfig.getIgnore(), String.class);
                    fdFollowConfigPageVo.setIgnoreList(ignoreList);
                }

                fdFollowConfigPageVoList.add(fdFollowConfigPageVo);
            }
        }
        //返回到页面分页对象
        Page<FdFollowConfigVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(fdFollowConfigPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询发单跟发配置详情
     *
     * @param fdFollowConfigIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public FdFollowConfigVo findFdFollowConfig(FdFollowConfigIdDto fdFollowConfigIdDto) {
        if (fdFollowConfigIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        FdFollowConfig fdFollowConfig = fdFollowConfigMapper.selectById(fdFollowConfigIdDto.getId(), fdFollowConfigIdDto.getMerId());

        if (fdFollowConfig == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该发单跟发配置不存在");
        }

        FdFollowConfigVo fdFollowConfigVo = new FdFollowConfigVo();
        BeanUtils.copyProperties(fdFollowConfig, fdFollowConfigVo);

        //封装关键词过滤
        if (StringUtils.isNotBlank(fdFollowConfig.getIgnore())) {
            List<String> ignoreList = JSONObject.parseArray(fdFollowConfig.getIgnore(), String.class);
            fdFollowConfigVo.setIgnoreList(ignoreList);
        }

        return fdFollowConfigVo;
    }

    /**
     * 添加发单跟发配置
     *
     * @param fdFollowConfigDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void addFdFollowConfig(FdFollowConfigDto fdFollowConfigDto) {

        Long merId = fdFollowConfigDto.getMerId();

        if (fdFollowConfigDto.getFdDevicePlanId() == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }


        if (fdFollowConfigDto.getFdDevicePlanId() == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        //查询该设备方案所有群信息
        FdDevicePlanIdDto pyqDevicePlanIdDto = new FdDevicePlanIdDto();
        pyqDevicePlanIdDto.setMerId(fdFollowConfigDto.getMerId());
        pyqDevicePlanIdDto.setId(fdFollowConfigDto.getFdDevicePlanId());
        FdDevicePlanVo fdDevicePlan = fdDevicePlanService.findFdDevicePlan(pyqDevicePlanIdDto);
        if (fdDevicePlan == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "设备方案不存在");
        }
        //查询该设备方案包含的群类型
        Set<String> deviceTypeList = fdDevicePlan.getDeviceTypeList();
        if (deviceTypeList != null && deviceTypeList.contains(DeviceTypeEnum.TIKTOK.getKey())) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该抖音群设备方案目前不支持跟发功能");
        }

        if (fdFollowConfigDto.getDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择监控机器人");
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdFollowConfigDto.getDeviceUniqueId(), null, fdFollowConfigDto.getMerId());
        if (device == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "监控机器人不存在");
        }

        if (StringUtils.isBlank(fdFollowConfigDto.getGroupId())) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入被监控群id");
        }

        if (StringUtils.isBlank(fdFollowConfigDto.getGroupUserWxid())) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入被监控群成员wxid");
        }

        //企业微信群
        String deviceType = "";
        String groupWxid = "";
        //String groupUserWxid = "";
        String groupUserId = "";
        if (device.getRecvmsgType().intValue() == DeviceTypeEnum.DT_WORK_WECHAT_VALUE || device.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE) {
            deviceType = DeviceTypeEnum.DT_WORK_WECHAT.getKey();
            //查询微信群
            String uzai_workwx_group_info = EsIndexName.UZAI_WORKWX_GROUP_INFO;
            uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(uzai_workwx_group_info, merId);
            //群主键merId_deviceId_wxid
            Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, fdFollowConfigDto.getGroupId(), null);
            EsWorkWxGroupInfo esWorkWxGroupInfo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
            if (esWorkWxGroupInfo == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此企业微信群不存在");
            }
            groupWxid = esWorkWxGroupInfo.getGroupId();
            //先查询出此群微信id在群中的成员信息
            //通过查询运营商其他索引分片获取分片索引
            String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, merId);

            //merId_groupWxid_wxid
            groupUserId = merId + "_" + groupWxid + "_" + fdFollowConfigDto.getGroupUserWxid();
            Map<String, Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, groupUserId, null);
            EsWorkWxGroupMember esWorkWxGroupMember = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWorkWxGroupMember.class);
            if (esWorkWxGroupMember == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群成员不存在");
            }
            //groupUserWxid = esWorkWxGroupMember.getWxid();

        } else {//个人微信群
            deviceType = DeviceTypeEnum.DT_PC_WECHAT.getKey();
            //查询微信群
            String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
            uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, merId);
            //群主键merId_deviceId_wxid
            Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, fdFollowConfigDto.getGroupId(), null);
            EsWxContacts esWxContacts = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
            if (esWxContacts == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此个人微信群不存在");
            }
            groupWxid = esWxContacts.getWxid();
            //先查询出此群微信id在群中的成员信息
            //通过查询运营商其他索引分片获取分片索引
            String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, merId);
            //merId_groupWxid_wxid
            groupUserId = merId + "_" + groupWxid + "_" + fdFollowConfigDto.getGroupUserWxid();
            Map<String, Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, groupUserId, null);
            EsWxGroupMember esWxGroupMember = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWxGroupMember.class);
            if (esWxGroupMember == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信群成员不存在");
            }
            //groupUserWxid = esWxGroupMember.getWxid();
        }

        FdFollowConfig fdFollowConfig_old = fdFollowConfigMapper.selectByDeviceUniqueIdAndGroupWxidAndGroupUserWxid(fdFollowConfigDto.getDeviceUniqueId(), groupWxid, fdFollowConfigDto.getGroupUserWxid());
        if (fdFollowConfig_old != null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "已经有任务配置了相同的[监控机器人]、[监控群]、[群成员]，此任务名称为：" + fdFollowConfig_old.getName());
        }

        Integer now = DateUtil.getNowTime();
        FdFollowConfig fdFollowConfig = new FdFollowConfig();
        fdFollowConfig.setId(IdWorker.getId());
        fdFollowConfig.setName(fdFollowConfigDto.getName());
        fdFollowConfig.setMerId(fdFollowConfigDto.getMerId());
        fdFollowConfig.setDeviceUniqueId(fdFollowConfigDto.getDeviceUniqueId());
        fdFollowConfig.setDeviceId(device.getDeviceId());
        fdFollowConfig.setDeviceType(deviceType);
        fdFollowConfig.setGroupId(fdFollowConfigDto.getGroupId());
        fdFollowConfig.setGroupWxid(groupWxid);
        fdFollowConfig.setGroupUserId(groupUserId);
        fdFollowConfig.setGroupUserWxid(fdFollowConfigDto.getGroupUserWxid());
        fdFollowConfig.setFdDevicePlanId(fdFollowConfigDto.getFdDevicePlanId());
        fdFollowConfig.setStatus(0); //默认关闭
        fdFollowConfig.setIgnore(Tools.getStrEmpty(JSONObject.toJSONString(fdFollowConfigDto.getIgnoreList())));
        fdFollowConfig.setImgSecret(Tools.getInteger(fdFollowConfigDto.getImgSecret()));
        fdFollowConfig.setEmoji(Tools.getInteger(fdFollowConfigDto.getEmoji()));
        fdFollowConfig.setTurnlink(Tools.getInteger(fdFollowConfigDto.getTurnlink()));
        fdFollowConfig.setTurnlinkDeal(Tools.getInteger(fdFollowConfigDto.getTurnlinkDeal()));
        fdFollowConfig.setLimitTimeStart(fdFollowConfigDto.getLimitTimeStart());
        fdFollowConfig.setLimitTimeEnd(fdFollowConfigDto.getLimitTimeEnd());
        fdFollowConfig.setCreateTime(now);
        fdFollowConfig.setUpdateTime(now);
        fdFollowConfigMapper.insert(fdFollowConfig);
    }

    /**
     * 修改发单跟发配置
     *
     * @param fdFollowConfigDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Transactional
    public void updateFdFollowConfig(FdFollowConfigDto fdFollowConfigDto) {

        Long merId = fdFollowConfigDto.getMerId();

        if (fdFollowConfigDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if (fdFollowConfigDto.getFdDevicePlanId() == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        //查询该设备方案所有群信息
        FdDevicePlanIdDto pyqDevicePlanIdDto = new FdDevicePlanIdDto();
        pyqDevicePlanIdDto.setMerId(fdFollowConfigDto.getMerId());
        pyqDevicePlanIdDto.setId(fdFollowConfigDto.getFdDevicePlanId());
        FdDevicePlanVo fdDevicePlan = fdDevicePlanService.findFdDevicePlan(pyqDevicePlanIdDto);
        if (fdDevicePlan == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "设备方案不存在");
        }
        //查询该设备方案包含的群类型
        Set<String> deviceTypeList = fdDevicePlan.getDeviceTypeList();
        if (deviceTypeList != null && deviceTypeList.contains(DeviceTypeEnum.TIKTOK.getKey())) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该抖音群设备方案目前不支持跟发功能");
        }

        if (fdFollowConfigDto.getDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择监控机器人");
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdFollowConfigDto.getDeviceUniqueId(), null, fdFollowConfigDto.getMerId());
        if (device == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "监控机器人不存在");
        }

        if (StringUtils.isBlank(fdFollowConfigDto.getGroupId())) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入被监控群id");
        }

        if (StringUtils.isBlank(fdFollowConfigDto.getGroupUserWxid())) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入被监控群成员wxid");
        }

        FdFollowConfig fdFollowConfig = fdFollowConfigMapper.selectById(fdFollowConfigDto.getId(), fdFollowConfigDto.getMerId());
        if (fdFollowConfig == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该跟发配置不存在");
        }

        //旧缓存Key
        String cacheKey_old = String.format(RedisCacheKeyEnum.FD_FOLLOW_TASK_CACHE_KEY.getKey(), fdFollowConfig.getMerId(), fdFollowConfig.getDeviceId(), fdFollowConfig.getGroupWxid(), fdFollowConfig.getGroupUserWxid());

        String deviceType = "";
        String groupWxid = "";
        //String groupUserWxid = "";
        String groupUserId = "";
        //企业微信群
        if (device.getRecvmsgType().intValue() == DeviceTypeEnum.DT_WORK_WECHAT_VALUE || device.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE) {
            deviceType = DeviceTypeEnum.DT_WORK_WECHAT.getKey();
            //查询微信群
            String uzai_workwx_group_info = EsIndexName.UZAI_WORKWX_GROUP_INFO;
            uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(uzai_workwx_group_info, merId);
            //群主键merId_deviceId_wxid
            Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, fdFollowConfigDto.getGroupId(), null);
            EsWorkWxGroupInfo esWorkWxGroupInfo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
            if (esWorkWxGroupInfo == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此企业微信群不存在");
            }
            groupWxid = esWorkWxGroupInfo.getGroupId();

            //先查询出此群微信id在群中的成员信息
            //通过查询运营商其他索引分片获取分片索引
            String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, merId);
            //merId_groupWxid_wxid
            groupUserId = merId + "_" + groupWxid + "_" + fdFollowConfigDto.getGroupUserWxid();
            Map<String, Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, groupUserId, null);
            EsWorkWxGroupMember esWorkWxGroupMember = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWorkWxGroupMember.class);
            if (esWorkWxGroupMember == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群成员不存在");
            }
            //groupUserWxid = esWorkWxGroupMember.getWxid();
        } else {//个人微信群
            deviceType = DeviceTypeEnum.DT_PC_WECHAT.getKey();
            //查询微信群
            String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
            uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, merId);
            //群主键merId_deviceId_wxid
            Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, fdFollowConfigDto.getGroupId(), null);
            EsWxContacts esWxContacts = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
            if (esWxContacts == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此个人微信群不存在");
            }
            groupWxid = esWxContacts.getWxid();

            //先查询出此群微信id在群中的成员信息
            //通过查询运营商其他索引分片获取分片索引
            String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, merId);
            //merId_groupWxid_wxid
            groupUserId = merId + "_" + groupWxid + "_" + fdFollowConfigDto.getGroupUserWxid();
            Map<String, Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, groupUserId, null);
            EsWxGroupMember esWxGroupMember = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWxGroupMember.class);
            if (esWxGroupMember == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信群成员不存在");
            }
            //groupUserWxid = esWxGroupMember.getWxid();
        }

        FdFollowConfig fdFollowConfig_old = fdFollowConfigMapper.selectByDeviceUniqueIdAndGroupWxidAndGroupUserWxid(fdFollowConfigDto.getDeviceUniqueId(), groupWxid, fdFollowConfigDto.getGroupUserWxid());
        if (fdFollowConfig_old != null && fdFollowConfig_old.getId().longValue() != fdFollowConfig.getId().longValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "已经有任务配置了相同的[监控机器人]、[监控群]、[群成员]，此任务名称为：" + fdFollowConfig_old.getName());
        }

        //是否发送修改跟发配置标志
        boolean sendFollowConfigFlag = false;

        fdFollowConfig.setMerId(fdFollowConfigDto.getMerId());
        fdFollowConfig.setName(fdFollowConfigDto.getName());

        if (fdFollowConfigDto.getDeviceUniqueId().longValue() != fdFollowConfig.getDeviceUniqueId().longValue()) {
            fdFollowConfig.setDeviceUniqueId(fdFollowConfigDto.getDeviceUniqueId());
            fdFollowConfig.setDeviceType(deviceType);
            fdFollowConfig.setDeviceId(device.getDeviceId());
            sendFollowConfigFlag = true;
        }

        String groupId = Tools.getStr(fdFollowConfigDto.getGroupId());
        if (!groupId.equals(fdFollowConfig.getGroupId())) {
            fdFollowConfig.setGroupId(groupId);
            fdFollowConfig.setGroupWxid(groupWxid);
            sendFollowConfigFlag = true;
        }

        String groupUserWxid = Tools.getStr(fdFollowConfigDto.getGroupUserWxid());
        if (!groupUserWxid.equals(fdFollowConfig.getGroupUserWxid())) {
            fdFollowConfig.setGroupUserId(groupUserId);
            fdFollowConfig.setGroupUserWxid(groupUserWxid);
            sendFollowConfigFlag = true;
        }

        fdFollowConfig.setFdDevicePlanId(fdFollowConfigDto.getFdDevicePlanId());
        fdFollowConfig.setIgnore(Tools.getStrEmpty(JSONObject.toJSONString(fdFollowConfigDto.getIgnoreList())));
        fdFollowConfig.setImgSecret(Tools.getInteger(fdFollowConfigDto.getImgSecret()));
        fdFollowConfig.setEmoji(Tools.getInteger(fdFollowConfigDto.getEmoji()));
        fdFollowConfig.setTurnlink(Tools.getInteger(fdFollowConfigDto.getTurnlink()));
        fdFollowConfig.setTurnlinkDeal(Tools.getInteger(fdFollowConfigDto.getTurnlinkDeal()));
        fdFollowConfig.setLimitTimeStart(fdFollowConfigDto.getLimitTimeStart());
        fdFollowConfig.setLimitTimeEnd(fdFollowConfigDto.getLimitTimeEnd());

        Integer now = DateUtil.getNowTime();
        fdFollowConfig.setUpdateTime(now);
        int i = fdFollowConfigMapper.updateById(fdFollowConfig);

        if (i == 1) { //修改成功
            //判断是否修改了监听机器人或者被监控微信wxid
            if (sendFollowConfigFlag) {
                //先删除旧的缓存
                redisTemplate.delete(cacheKey_old);
                //更新缓存
                String cacheKey_new = String.format(RedisCacheKeyEnum.FD_FOLLOW_TASK_CACHE_KEY.getKey(), fdFollowConfig.getMerId(), fdFollowConfig.getDeviceId(), fdFollowConfig.getGroupWxid(), fdFollowConfig.getGroupUserWxid());
                if (Tools.getInteger(fdFollowConfig.getStatus()).intValue() == 0) { //关闭，删除
                    redisTemplate.delete(cacheKey_new);
                } else {//开启-增加
                    redisTemplate.opsForValue().set(cacheKey_new, true);
                }
            }
        }
    }

    /**
     * 删除
     *
     * @param fdFollowConfigIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Transactional
    public void deleteFdFollowConfig(FdFollowConfigIdDto fdFollowConfigIdDto) {
        if (fdFollowConfigIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        FdFollowConfig fdFollowConfig = fdFollowConfigMapper.selectById(fdFollowConfigIdDto.getId(), fdFollowConfigIdDto.getMerId());

        if (fdFollowConfig == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此跟发配置不存在");
        }
        //删除
        fdFollowConfigMapper.deleteById(fdFollowConfigIdDto.getId(), fdFollowConfigIdDto.getMerId());

        //删除缓存
        String cacheKey = String.format(RedisCacheKeyEnum.FD_FOLLOW_TASK_CACHE_KEY.getKey(), fdFollowConfig.getMerId(), fdFollowConfig.getDeviceId(), fdFollowConfig.getGroupWxid(), fdFollowConfig.getGroupUserWxid());
        redisTemplate.delete(cacheKey);
    }

    /**
     * 设置是否开启
     *
     * @param fdFollowConfigStatusDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Transactional
    public void updateStatus(FdFollowConfigStatusDto fdFollowConfigStatusDto) {

        if (fdFollowConfigStatusDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        FdFollowConfig fdFollowConfig = fdFollowConfigMapper.selectById(fdFollowConfigStatusDto.getId(), fdFollowConfigStatusDto.getMerId());

        if (fdFollowConfig == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此跟发配置不存在");
        }

        if (fdFollowConfig.getDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "监控机器人唯一id不能为空");
        }

        Long merId = fdFollowConfig.getMerId();

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdFollowConfig.getDeviceUniqueId(), null, fdFollowConfig.getMerId());
        if (device == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "监控机器人不存在");
        }

        if (StringUtils.isBlank(fdFollowConfig.getGroupId())) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入被监控群id");
        }

        if (StringUtils.isBlank(fdFollowConfig.getGroupUserId())) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入被监控群成员id");
        }

        fdFollowConfig.setStatus(Tools.getInteger(fdFollowConfigStatusDto.getStatus()));

        //修改状态
        int i = fdFollowConfigMapper.updateStatusById(fdFollowConfig);
        //修改成功
        if (i == 1) {
            if (Tools.getInteger(fdFollowConfigStatusDto.getStatus()).intValue() == 0) { //关闭
                String cacheKey = String.format(RedisCacheKeyEnum.FD_FOLLOW_TASK_CACHE_KEY.getKey(), fdFollowConfig.getMerId(), fdFollowConfig.getDeviceId(), fdFollowConfig.getGroupWxid(), fdFollowConfig.getGroupUserWxid());
                redisTemplate.delete(cacheKey);
            } else { //开启
                String deviceType = "";
                String groupWxid = "";
                String groupUserWxid = "";
                //企业微信群
                if (device.getRecvmsgType().intValue() == DeviceTypeEnum.DT_WORK_WECHAT_VALUE || device.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE) {
                    //查询微信群
                    String uzai_workwx_group_info = EsIndexName.UZAI_WORKWX_GROUP_INFO;
                    uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(uzai_workwx_group_info, merId);
                    //群主键merId_deviceId_wxid
                    Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, fdFollowConfig.getGroupId(), null);
                    EsWorkWxGroupInfo esWorkWxGroupInfo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
                    if (esWorkWxGroupInfo == null) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此企业微信群不存在");
                    }
                    groupWxid = esWorkWxGroupInfo.getGroupId();
                    //先查询出此群微信id在群中的成员信息
                    //通过查询运营商其他索引分片获取分片索引
                    String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, merId);
                    Map<String, Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, fdFollowConfig.getGroupUserId(), null);
                    EsWorkWxGroupMember esWorkWxGroupMember = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWorkWxGroupMember.class);
                    if (esWorkWxGroupMember == null) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群成员不存在");
                    }
                    groupUserWxid = esWorkWxGroupMember.getWxid();
                } else {//个人微信群
                    //查询微信群
                    String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
                    uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, merId);
                    //群主键merId_deviceId_wxid
                    Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, fdFollowConfig.getGroupId(), null);
                    EsWxContacts esWxContacts = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
                    if (esWxContacts == null) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此个人微信群不存在");
                    }
                    groupWxid = esWxContacts.getWxid();
                    //先查询出此群微信id在群中的成员信息
                    //通过查询运营商其他索引分片获取分片索引
                    String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, merId);
                    Map<String, Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, fdFollowConfig.getGroupUserId(), null);
                    EsWxGroupMember esWxGroupMember = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWxGroupMember.class);
                    if (esWxGroupMember == null) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信群成员不存在");
                    }
                    groupUserWxid = esWxGroupMember.getWxid();
                }
                String cacheKey = String.format(RedisCacheKeyEnum.FD_FOLLOW_TASK_CACHE_KEY.getKey(), fdFollowConfig.getMerId(), fdFollowConfig.getDeviceId(), groupWxid, groupUserWxid);
                //更新缓存
                redisTemplate.opsForValue().set(cacheKey, true);
            }
        } else {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络延迟");
        }
    }

    /**
     * 刷新是否下载图片的发单微信群id列表
     *
     * @param refreshDownloadImgGroupWxidListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public String refreshDownloadImgGroupWxidList(RefreshDownloadImgGroupWxidListDto refreshDownloadImgGroupWxidListDto) {
        Long merId = refreshDownloadImgGroupWxidListDto.getMerId();
        if (merId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入运营商id");
        }

        //查询运营商所有发单跟发启动的任务
        List<String> groupWxidList = new ArrayList<>();
        FdFollowConfigQuery fdFollowConfigQuery = new FdFollowConfigQuery();
        fdFollowConfigQuery.setMerId(merId);
        fdFollowConfigQuery.setStatus(1); //启动的任务
        ArrayList<FdFollowConfig> fdFollowConfigList = fdFollowConfigMapper.findByList(fdFollowConfigQuery);
        if (fdFollowConfigList != null && fdFollowConfigList.size() > 0) {
            for (FdFollowConfig fdFollowConfig : fdFollowConfigList) {
                groupWxidList.add(fdFollowConfig.getGroupWxid());
            }
        }

        //保存到缓存当中，有效期一个月
        String cacheKey = String.format(RedisCacheKeyEnum.FD_FOLLOW_TASK_GROUPWXID_LIST_DOWNLOAD_IMG.getKey(), merId);
        redisTemplate.opsForValue().set(cacheKey, JSONObject.toJSONString(groupWxidList), 30, TimeUnit.DAYS);

        return JSONObject.toJSONString(groupWxidList);
    }
}
